package com.elcl.widget.comp.scrollview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * @author lichunlin 功能点 1、可以左滑返回的问题，详情见dealMotion、judgeFlingDirection
 *         2、当嵌套viewpager的时候，解决冲突问题
 */
public class MScrollView extends ScrollView {
	private Context context;

	public MScrollView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
	}

	public MScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	public MScrollView(Context context) {
		super(context);
		this.context = context;
	}

	private float oldx;
	private float x;
	private int SMOOTH_Y = 160;// 横向滑动的距离
	private boolean isScrollBack = false;// 左滑返回的效果

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			oldx = event.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			x = event.getX();
			dealMotion();
			break;
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 左右有关手势的操作都在这里
	 */
	private void dealMotion() {
		if (isScrollBack) {// 如果允许左滑返回的话，
			judgeFlingDirection();
		}
	}

	/**
	 * 左滑动返回,默认动画为被滑动的界面，从右边出去
	 */
	private void judgeFlingDirection() {// 判断滑动的方向
		if (x - oldx > SMOOTH_Y) {// 左滑动返回
			((Activity) context).finish();
			// ((Activity) context).overridePendingTransition(enterAnim,
			// exitAnim);
		}
	}

	/**
	 * 设置可以左滑返回的事件
	 */
	public void enableScrollBack() {
		isScrollBack = true;
	}

	private float xDistance, yDistance, xLast, yLast;

	/**
	 * 当嵌套viewpager的时候，解决冲突问题
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			xDistance = yDistance = 0f;
			xLast = ev.getX();
			yLast = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			final float curX = ev.getX();
			final float curY = ev.getY();

			xDistance += Math.abs(curX - xLast);
			yDistance += Math.abs(curY - yLast);
			xLast = curX;
			yLast = curY;

			if (xDistance > yDistance) {
				return false;
			}
		}
		return super.onInterceptTouchEvent(ev);
	}

}
